package com.sl.spring.intergration.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.sl.spring.intergration.vo.IMoocJSONResult;

@ControllerAdvice
public class IExceptionHandler {

	private static final String IMOOC_ERROR_VIEW = "error";

	@ExceptionHandler(value = Exception.class)
	public Object handler(HttpServletRequest reqest,
			HttpServletResponse response, Exception e) {
		
		e.printStackTrace();

		if (isAjax(reqest)) {
			return IMoocJSONResult.errorException(e.getMessage());
		} else {
			ModelAndView mav = new ModelAndView();
			mav.addObject("exception", e);
			mav.addObject("url", reqest.getRequestURL());
			mav.setViewName(IMOOC_ERROR_VIEW);
			return mav;
		}
	}

	private boolean isAjax(HttpServletRequest httpRequest) {
		return (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest"
				.equals(httpRequest.getHeader("X-Requested-With").toString()));
	}
}
